package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;

import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        if(StringUtils.isBlank(name)||StringUtils.isBlank(password)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        if(9!=adUser.getStatus()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //获取数据库内加密的密码和盐
        String oldPassword = adUser.getPassword();
        String salt = adUser.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!oldPassword.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误");
        }
        //修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //颁发token jwt 令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        //构建返回值
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
